package com.sloera.dispatch;

import com.sloera.dto.RPCTransformObj;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ServiceDispatch {
    /*
     * @Description 服务的分发
     * @param object:  请求对象
     * @Return java.lang.Object
     * @Author SloeraN
     * @Date 2020/3/18 0:25
     */
    public static Object dispatch(Object object) {
        RPCTransformObj reqObj = (RPCTransformObj) object;
        String classPath = reqObj.getClassPath();
        String methodName = reqObj.getMethodName();
        Object[] params = reqObj.getParams();
        Class[] types = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            types[i] = params[i].getClass();
        }

        Object respObj = null;
        // 反射的方法调用
        try {
            Class clazz = Class.forName(classPath);
            Method method = clazz.getDeclaredMethod(methodName, types); //获取方法
            respObj = method.invoke(clazz.newInstance(), params);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return respObj;
    }
}
